package org.jppf.application.template2;

import java.util.ArrayList;
import java.util.List;

import org.jppf.client.JPPFClient;
import org.jppf.client.JPPFConnectionPool;
import org.jppf.client.JPPFJob;
import org.jppf.client.Operator;
import org.jppf.node.protocol.Task;

public class JPPFMain4 {

	public static void main(String[] args) {
		Timer t = new Timer();
		t.start();
		try (JPPFClient jppfClient = new JPPFClient()) {
			
			int connectionPoolSize = 10;
			int numberOfJobs = 100;
			int numberOfTasks = 5;
			
			JPPFConnectionPool pool = jppfClient.awaitActiveConnectionPool();
			pool.setSize(connectionPoolSize);
			pool.awaitActiveConnections(Operator.AT_LEAST, connectionPoolSize);
			
			List<JPPFJob> jobList = new ArrayList<JPPFJob>();
			
			for(int i = 0; i < numberOfJobs; i++) {
			
				JPPFJob job = new JPPFJob();
				job.setBlocking(false);
				job.setName("Job: " + i);
				
				for(int j = 0; j < numberOfTasks; j++) {
					job.add(new JPPFTask("Task " + ((i * numberOfTasks) + j), 4));
				}
				jppfClient.submitJob(job);
				jobList.add(job);
			}
			
			for(JPPFJob job: jobList) {
			
				List<Task<?>> results = job.awaitResults();

				for (Task<?> task: results) {
					String taskId = task.getId();
					
					if (task.getThrowable() == null) {
						System.out.println("Execution result: " + task.getResult());
					} else {
						System.out.println(taskId + ", an exception was raised: " + task.getThrowable().getMessage());
					}
				}
			}

		} catch(Exception e) {
			e.printStackTrace();
		}
		t.time();
	}
}
